/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useRef, useEffect, useCallback } from "react";
import { Chart, Geom, Axis, Tooltip, Legend } from "bizcharts";
import { useDispatch, useSelector } from "dva";
import moment from "moment";
import DataSet from "@antv/data-set";
import CommonBorder from "./Wrappers/CommonBorder";
import NoDate from "./Wrappers/NoDate";
import { axisLabel } from "./_utils";
import styles from "./SliderChart.less";

const scale = {
  date: {
    tickCount: 10,
    nice: true,
  },
  number: {
    nice: true,
  },
};

const getToolLi = data => {
  let str = "";
  data.forEach(item => {
    str += `<li style="color:${item.color}">${item.name}：${item.value}</li>`;
  });
  return str;
};

const ds = new DataSet();
const fieldsPool = ["arrive_num", "out_num", "in_num", "send_num"];
const initLegend = [
  { value: "arrive_num", fill: "#ff756b", marker: "hyphen" },
  { value: "out_num", fill: "#d8af30", marker: "hyphen" },
  { value: "in_num", fill: "#3591e6", marker: "hyphen" },
  { value: "send_num", fill: "#19c0b7", marker: "hyphen" },
];

const SliderChart = ({ isParentFull }) => {
  const dispatch = useDispatch();
  const token = useSelector(({ global } = {}) => global.screenToken);
  const yzLegendsMap = useSelector(({ chartData } = {}) => chartData.yzLegendsMap);
  const yzLegendsMapKey = Object.keys(yzLegendsMap);

  const [list, setList] = useState([]);
  const [hasData, setHasData] = useState(false);
  const [height, setHeight] = useState(0);
  const [customLegend, setCustomLegend] = useState(initLegend);
  const heightRef = useRef({});
  const timer = useRef(null);

  const handleTooltipChange = ev => {
    ev.items.forEach(data => {
      data.name = yzLegendsMap ? yzLegendsMap[data.name].label : data.name;
    });
  };

  useEffect(
    () => {
      timer.current = setTimeout(() => {
        heightRef.current && setHeight(heightRef.current.clientHeight);
      }, 1000);

      return () => {
        timer.current && clearTimeout(timer.current);
      };
    },
    [isParentFull]
  );

  const requestCallback = useCallback(
    () =>
      dispatch({
        type: "chartData/getRealTimeChart",
        payload: { token },
      }),
    [dispatch, token]
  );

  const onSuccess = data => {
    const val = ds
      .createView()
      .source(data)
      .transform({
        type: "fold",
        fields: Object.keys(yzLegendsMap),
        key: "city",
        value: "number",
      });
    // 更新legend，防止颜色不对
    setCustomLegend(prevLegend => {
      return prevLegend.filter(v => yzLegendsMapKey.includes(v.value));
    });
    setList(val);
    setHasData(data.length > 0);
  };

  const onError = () => {
    setHasData(false);
  };

  const onLegendClick = ev => {
    const { checked, item = {} } = ev;
    const { value } = item;
    const originList = list.origin;

    if (checked && !fieldsPool.includes(value)) {
      fieldsPool.push(value);
    } else {
      fieldsPool.forEach((val, index) => {
        if (val == value) {
          fieldsPool.splice(index, 1);
        }
      });
    }

    const val = ds
      .createView()
      .source(originList)
      .transform({
        type: "pick",
        fields: ["date", ...fieldsPool],
      })
      .transform({
        type: "fold",
        fields: Object.keys(yzLegendsMap),
        key: "city",
        value: "number",
      });
    // 更新legend
    setCustomLegend(prevList => {
      prevList.forEach(val => {
        val.value === value;
        val.fill = checked ? val.fill : "";
      });
      return prevList;
    });
    setList(val);
  };

  return (
    <CommonBorder
      title="今日实时数据"
      showProgress
      delay={600}
      requestCallback={requestCallback}
      onSuccess={onSuccess}
      onError={onError}
    >
      <div className={styles.sliderChart} style={{ height: "100%" }} ref={heightRef}>
        {hasData ? (
          <Chart
            style={{ backgroundColor: "rgba(15, 24, 55, 0.6)" }}
            onTooltipChange={handleTooltipChange}
            color="name"
            height={height}
            data={list}
            forceFit
            padding={[50, "auto", "auto", "auto"]}
            scale={scale}
          >
            <Legend
              name="city"
              itemFormatter={text => {
                return (yzLegendsMap[text] && yzLegendsMap[text].label) || text;
              }}
              position="top-right"
              custom
              items={customLegend}
              useHtml
              itemTpl={`
              <li class="g2-legend-list-item item-{index}" data-color="{originColor}" data-value="{originValue}">
                <span class="g2-legend-text g2-legend-text_val" style="color: {color};">{value}</span>
                <i class="g2-legend-marker" style="background-color: {color};"></i>
              </li>`}
              g2-legend={{
                paddingBottom: "10px",
              }}
              g2-legend-list={{
                textAlign: "right",
              }}
              g2-legend-list-item={{
                fontSize: "18px",
                verticalAlign: "middle",
              }}
              g2-legend-marker={{
                width: "40px",
                height: "4px",
                borderRadius: "5px",
              }}
              onClick={onLegendClick}
            />
            <Axis
              line={{
                fill: "#3651ab",
              }}
              name="date"
              label={{
                ...axisLabel,
                formatter: val => moment(val).format("HH:mm"),
              }}
              tickLine={null}
            />
            <Axis
              line={{
                fill: "#3651ab",
              }}
              grid={null}
              name="number"
              label={{
                ...axisLabel,
                formatter: val => (val > 10000 ? `${Math.round(val / 10000)}万` : val),
              }}
            />
            <Tooltip
              crosshairs={{
                type: "y",
              }}
              useHtml
              htmlContent={(title, items) => {
                const lis = getToolLi(items);
                const timeTitle = moment(title).format("HH:mm");
                return `<div class="g2-tooltip" style='position:absolute;'>
                  <div class="g2-tooltip-title" style="color:#4667d2">${timeTitle}</div>
                  <ul>${lis}</ul>
                </div>`;
              }}
            />
            <Geom
              type="line"
              position="date*number"
              color={["city", ["#ff756b", "#d8af30", "#3591e6", "#19c0b7"]]}
              size={2}
              shape="smooth"
            />
          </Chart>
        ) : (
          <NoDate title="暂无数据" style={{ height }} />
        )}
      </div>
    </CommonBorder>
  );
};

export default SliderChart;
